Total Complexity | 7 |
Total Lines | 38 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | import {IObserver} from '../Observer/Observer'; |
||
9 | |||
10 | export default class Router { |
||
11 | currentPage: IObserver<IPageData | null>; |
||
12 | history: History; |
||
13 | |||
14 | constructor(pageObserver: IObserver<IPageData | null>, history: History) { |
||
15 | 6 | this.currentPage = pageObserver; |
|
16 | 6 | this.history = history; |
|
17 | } |
||
18 | |||
19 | attachTo(window: Window) { |
||
20 | 3 | window.addEventListener('popstate', this.onHistoryChange.bind(this)); |
|
21 | } |
||
22 | |||
23 | initialize(): void { |
||
24 | 3 | if (this.currentPage.value == null) return; |
|
25 | 1 | const firstPage: IPageData = this.currentPage.value; |
|
26 | 1 | this.history.replaceState(firstPage, firstPage.name, firstPage.rootUrl); |
|
27 | 1 | this.updatePage(firstPage); |
|
28 | } |
||
29 | |||
30 | changePage(newPage: IPageData): void { |
||
31 | 2 | const currentPage: IPageData | null = this.currentPage.value; |
|
32 | 4 | if (currentPage != null && currentPage.name == newPage.name) { |
|
33 | 1 | return; |
|
34 | } |
||
35 | |||
36 | 1 | this.history.replaceState(newPage, newPage.name, newPage.url); |
|
37 | 1 | this.updatePage(newPage); |
|
38 | } |
||
39 | |||
40 | updatePage(page: IPageData): void { |
||
41 | 3 | this.currentPage.value = page; |
|
42 | } |
||
43 | |||
44 | onHistoryChange(event: PopStateEvent): void { |
||
45 | 1 | const newPage: IPageData = event.state as IPageData; |
|
46 | 1 | this.updatePage(newPage); |
|
47 | } |
||
49 |